package chapter7.JDBCpart;

import org.junit.jupiter.api.Test;

import java.sql.*;

/**
 * @Project ：learn_java
 * @File ：DriverManagerDemo04.java
 * @IDE ：IntelliJ IDEA
 * @Author ：自由如风间
 * @Date ：2025/3/21 17:34
 * @Description ：jdbc api中的 preparedStatement
 * preparedStatement作用：预编译SQL语句并执行，预防SQL注入问题
 */

public class DriverManagerDemo04 {

    @Test
    public void testPreparedStatement() throws SQLException {
        String url = "jdbc:mysql:///study?useSSL=false";
        String username = "root";
        String password = "root";

        Connection conn = DriverManager.getConnection(url, username, password);

        // 定义sql
        String sql = "select * from account";

        Statement stmt = conn.createStatement();

        ResultSet rs = stmt.executeQuery(sql);

        while (rs.next()) {
            /**
             * 获取数据
             */

            // 列获取
            // int id = rs.getInt(1);
            // String name = rs.getString(2);
            // double money = rs.getDouble(3);

            // 也可以用label获取
            int id = rs.getInt("id");
            String name = rs.getString("name");
            double money = rs.getDouble("money");

            System.out.println(id);
            System.out.println(name);
            System.out.println(money);

            // 间隔行
            System.out.println("-".repeat(20));
        }

        // 释放资源
        rs.close();
        stmt.close();
        conn.close();
    }
}
